package com.glzn.springboot03.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lenovo
 */
@Configuration
public class HttpSessionConfig {
	private static final Map<String, HttpSession> sessions = new HashMap<>();

	@Autowired
	RedisTemplate redisTemplate;

	public static List<HttpSession> getActiveSessions() {
		return new ArrayList<>(sessions.values());
	}

	@Bean
	public HttpSessionListener httpSessionListener() {
		return new HttpSessionListener() {
			@Override
			public void sessionCreated(HttpSessionEvent hse) {
				System.out.println("session 创建,ID:"+hse.getSession().getId());
				sessions.put(hse.getSession().getId(), hse.getSession());
			}

			@Override
			public void sessionDestroyed(HttpSessionEvent hse) {
				HttpSession session = hse.getSession();
				System.out.println("session 销毁, ID:"+session.getId());
				Integer deviceId = (Integer) session.getAttribute("device_id");
				// 删除缓存
				redisTemplate.opsForList().remove("device_id", 0, deviceId);
				redisTemplate.delete(session.getId());

				sessions.remove(session.getId());
			}
		};
	}
}
